package by.dkusch.aircompany.webapp.page.base.utils;

import java.util.Iterator;

import by.dkusch.aircompany.model.tables.UserGrant;
import by.dkusch.aircompany.model.tables.enums.FormType;
import by.dkusch.aircompany.webapp.app.BasicAuthenticationSession;
import by.dkusch.aircompany.webapp.page.base.enums.ActionType;

public class GrantsResolver {
	public final static int NO_ACCESS = 0;
	public final static int VIEW_ONLY = 1;
	public final static int EDIT_NO_DELETE = 2;
	public final static int EDIT_WITH_DELETE = 3;

	public static int accessLevel(Class<?> target) {

		String simpleName = target.getSimpleName();

		if (BasicAuthenticationSession.get().isUserDba()) {
			return EDIT_WITH_DELETE;
		}

		try {
			FormType ft = FormType.valueOf(simpleName);

			UserGrant foundGrant = null;

			for (Iterator<UserGrant> it = BasicAuthenticationSession.get().getUserGrants().iterator(); it.hasNext();) {
				UserGrant f = it.next();
				if (f.getFormId().equals(ft)) {
					foundGrant = f;
					break;
				}
			}
			if (foundGrant != null) {
				if (foundGrant.getEditFl() && !foundGrant.getDeleteFl()) {
					return EDIT_NO_DELETE;
				}
				if (foundGrant.getEditFl() && foundGrant.getDeleteFl()) {
					return EDIT_WITH_DELETE;
				}
				if (!foundGrant.getEditFl() && foundGrant.getViewFl()) {
					return VIEW_ONLY;
				}
			}

		} catch (IllegalArgumentException ex) {

		}
		return NO_ACCESS;
	}

	public static boolean canDo(Class<?> target, ActionType action) {
		if (BasicAuthenticationSession.get().isSignedIn()) {
			int access = accessLevel(target);
			switch (access) {
			case EDIT_WITH_DELETE:
				return true;
			case EDIT_NO_DELETE:
				return !ActionType.REMOVE.equals(action);
			case VIEW_ONLY:
				return ActionType.VIEW.equals(action);
			default:
				return false;
			}
		}
		return false;
	}
}
